/**
 * Project  : Looker
 * Package  : net.freestu.looker.monitor
 * File     : FetcherGroup.java
 * Author   : solosky < solosky772@qq.com >
 * Date     : Aug 23, 2009
 * Modified : Aug 23, 2009
 * License  : Apache License 2.0 
 */
package net.freestu.looker.monitor;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.concurrent.CountDownLatch;

import net.freestu.looker.common.Looker;

/**
 *  工具类，以下载器为组管理下载
 */
public class FetcherGroup
{
	/**
	 * 下载器列表
	 */
	private ArrayList<AbstractFetcher> fetcherList;
	
	/**
	 * 闭锁，判断是否下载完成
	 */
	private CountDownLatch latch;
	/**
	 * 构造函数
	 */
	public FetcherGroup()
	{
		this.fetcherList = new ArrayList<AbstractFetcher>();
	}
	
	/**
	 * 添加下载器
	 */
	public void addFetcher(AbstractFetcher fetcher)
	{
		this.fetcherList.add(fetcher);
	}
	
	/**
	 * 启动下载
	 */
	public void start()
	{
		setLatch();
		submit();
	}
	
	/**
	 * 等待所有的线程完成
	 * @throws InterruptedException 
	 */
	public void await() throws InterruptedException
	{
		latch.await();
	}
	
	/**
	 * 设置闭锁
	 */
	private void setLatch()
	{
		latch = new CountDownLatch(fetcherList.size()); 
		Iterator<AbstractFetcher> it = fetcherList.iterator();
		while(it.hasNext())
			it.next().setLatch(latch);
	}
	
	/**
	 * 提交至线程池处理
	 */
	private void submit()
	{
		Iterator<AbstractFetcher> it = fetcherList.iterator();
		while(it.hasNext())
			Looker.executors.submit(it.next());
	}
}
